package com.kuaifawu.lwnlawyerclient.Fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.Activity.LWNLoginActivity;
import com.kuaifawu.lwnlawyerclient.Activity.LWNQuestionDetailActivity;
import com.kuaifawu.lwnlawyerclient.Activity.MainActivity;
import com.kuaifawu.lwnlawyerclient.Adapter.LWNAdapter_myQuestionList;
import com.kuaifawu.lwnlawyerclient.Lib.LWNJsonToData;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_myQuestion;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_user;
import com.kuaifawu.lwnlawyerclient.R;
import com.kuaifawu.lwnlawyerclient.Lib.LWNSwip.LWSwipeRefreshLayout;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

//我的问题列表

public class LWNMyQuestionFragment extends Fragment implements LWSwipeRefreshLayout.OnRefreshListener,LWSwipeRefreshLayout.OnLoadListener {
    @ViewInject(R.id.listView_myQuestion)
    private ListView listView_myquestion;

    private ArrayList<LWNModel_myQuestion> array_myQuestion;
    private ArrayList<LWNModel_myQuestion> array_AllmyQuestion;
    LayoutInflater mInflater;
    MainActivity activity_self;
    private LWSwipeRefreshLayout myQuestion_data_refresh;
    private int start=0;
    private LWSwipeRefreshLayout nulldata_refreshquestion;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mInflater = inflater;
        View rootView = inflater.inflate(R.layout.fragment_my_question, container, false);
        ViewUtils.inject(this, rootView);
        myQuestion_data_refresh=(LWSwipeRefreshLayout)rootView.findViewById(R.id.myQuestion_data_refresh);
        nulldata_refreshquestion = (LWSwipeRefreshLayout) rootView.findViewById(R.id.nulldata_refreshquestion);
        array_AllmyQuestion=new ArrayList<LWNModel_myQuestion>();
        setRefresh();
        getMyQuestionFromNetwork();
        return rootView;
    }

    public void LoadMyQuestionDataWithActivity(MainActivity activity_main) {
        activity_self = activity_main;


           // getMyQuestionFromNetwork();


    }


    private void setRefresh(){
        myQuestion_data_refresh.setColor(android.R.color.holo_blue_light,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        myQuestion_data_refresh.setMode(LWSwipeRefreshLayout.Mode.BOTH);
        myQuestion_data_refresh.setLoadNoFull(false);
        myQuestion_data_refresh.setOnRefreshListener(this);
        myQuestion_data_refresh.setOnLoadListener(this);
        myQuestion_data_refresh.setRefreshing(true);



        nulldata_refreshquestion.setColor(android.R.color.holo_blue_light,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        nulldata_refreshquestion.setMode(LWSwipeRefreshLayout.Mode.BOTH);
        nulldata_refreshquestion.setLoadNoFull(false);
        nulldata_refreshquestion.setOnRefreshListener(this);
        nulldata_refreshquestion.setOnLoadListener(this);

    }
    @Override
    public void onLoad() {
        start=start+20;
        getMyQuestionFromNetwork();

    }

    @Override
    public void onRefresh() {
        start=0;
        getMyQuestionFromNetwork();

    }

    private void getMyQuestionFromNetwork(){
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        if(!center.checkNetworkState(activity_self)){
            ToastView_custom toast = new ToastView_custom(activity_self);
            toast.showCustom(activity_self, "检查网络，稍后重试");
            myQuestion_data_refresh.setLoading(false);
            myQuestion_data_refresh.setRefreshing(false);
            return;
        }
        String string_url = center.getInstance().getMyQusetion(start+"", "20", activity_self);
        //System.out.println(string_url);
        HttpUtils http = center.getUtils();
        http.configDefaultHttpCacheExpiry(0*0);
        http.send(HttpRequest.HttpMethod.GET,
                string_url,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        myQuestion_data_refresh.setLoading(false);
                        myQuestion_data_refresh.setRefreshing(false);
                        nulldata_refreshquestion.setRefreshing(false);
                      //  proDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            String string_msg = jsonObject.getString("msg");

                            //System.out.println(string_code);
                            switch (String.valueOf(string_code)) {
                                case "10000": {
                                    nulldata_refreshquestion.setVisibility(View.GONE);
                                    myQuestion_data_refresh.setVisibility(View.VISIBLE);
                                    JSONArray json_array = jsonObject.getJSONArray("data");
                                    array_myQuestion = LWNJsonToData.getMyQuestionWithJsonString(json_array);
                                    if(start==0){
                                        if(array_AllmyQuestion.size()!=0){
                                            array_AllmyQuestion.clear();
                                        }
                                        array_AllmyQuestion.addAll(array_myQuestion);
                                    } else{
                                        array_AllmyQuestion.addAll(array_myQuestion);
                                    }
                                    InitListContent();
                                }
                                break;
                                case "10001": {
//                                    Toast toast = Toast.makeText(activity_self.getApplicationContext(),
//                                            string_msg, Toast.LENGTH_SHORT);
//                                    toast.setGravity(Gravity.CENTER, 0, 0);
//                                    LinearLayout toastView = (LinearLayout) toast.getView();
//                                    ImageView imageCodeProject = new ImageView(activity_self.getApplicationContext());
//                                    imageCodeProject.setImageResource(R.drawable.error);
//                                    toastView.addView(imageCodeProject, 0);
//                                    toast.show();
                                    ToastView_custom toast = new ToastView_custom(activity_self.getApplicationContext());
                                    toast.showCustom(activity_self,string_msg);
                                }
                                break;
                                case "10003": {
                                    String token = LWNModel_user.getInstance().getString_token(activity_self);
                                    if (token != null) {
//                                        Toast toast = Toast.makeText(activity_self.getApplicationContext(),
//                                                string_msg, Toast.LENGTH_SHORT);
//                                        toast.setGravity(Gravity.CENTER, 0, 0);
//                                        LinearLayout toastView = (LinearLayout) toast.getView();
//                                        ImageView imageCodeProject = new ImageView(activity_self.getApplicationContext());
//                                        imageCodeProject.setImageResource(R.drawable.error);
//                                        toastView.addView(imageCodeProject, 0);
//                                        toast.show();

                                        ToastView_custom toast = new ToastView_custom(activity_self);
                                        toast.showCustom(activity_self,  "未登录");

                                        Intent intent = new Intent();
                                        intent.putExtra("name", "LeiPei");
                                        intent.setClass(activity_self, LWNLoginActivity.class);
                                        startActivity(intent);
                                        activity_self.finish();
                                    }
                                }
                                break;
                                case "10009":
                                    ToastView_custom toast123 = new ToastView_custom(activity_self);
                                    toast123.showCustom(activity_self, string_msg);
                                    if(start==0){
                                        nulldata_refreshquestion.setVisibility(View.VISIBLE);
                                        myQuestion_data_refresh.setVisibility(View.GONE);
                                    }

                                default: {
//                                    Toast toast = Toast.makeText(activity_self.getApplicationContext(),
//                                            string_msg, Toast.LENGTH_SHORT);
//                                    toast.setGravity(Gravity.CENTER, 0, 0);
//                                    LinearLayout toastView = (LinearLayout) toast.getView();
//                                    ImageView imageCodeProject = new ImageView(activity_self.getApplicationContext());
//                                    imageCodeProject.setImageResource(R.drawable.error);
//                                    toastView.addView(imageCodeProject, 0);
//                                    toast.show();
                                    ToastView_custom toast = new ToastView_custom(activity_self.getApplicationContext());
                                    toast.showCustom(activity_self,string_msg);
                                }
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            //proDialog.dismiss();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        //System.out.println(s);
                        if(myQuestion_data_refresh!=null&&myQuestion_data_refresh.isLoading()){
                            myQuestion_data_refresh.setLoading(false);
                        }
                        if(myQuestion_data_refresh!=null&&myQuestion_data_refresh.isRefreshing()){
                            myQuestion_data_refresh.setRefreshing(false);
                        }

                      //  proDialog.dismiss();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }
private LWNAdapter_myQuestionList adapter_myquestion =null;
    public void InitListContent(){
        listView_myquestion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectMyquestionItem(position);
            }
        });

        View fragment_myquestion = mInflater.inflate(R.layout.fragment_my_question, null);



        if(adapter_myquestion==null){
            adapter_myquestion = new LWNAdapter_myQuestionList(fragment_myquestion.getContext(), R.layout.fragment_my_question, array_AllmyQuestion);
            listView_myquestion.setAdapter(adapter_myquestion);
        }else{
            adapter_myquestion.notifyDataSetChanged();
        }
    }

    //点击列表
    public void selectMyquestionItem(int position){
        Intent intent = new Intent();
        LWNModel_myQuestion model_myquestion = array_AllmyQuestion.get(position);
        Bundle bundle=new Bundle();
        bundle.putString("questionid",model_myquestion.getId());
        bundle.putString("questionsolve", model_myquestion.getIs_solve());
        intent.putExtras(bundle);
//        intent.putExtra("questionid", model_myquestion.getId());
//        intent.putExtra("questionsolve", model_myquestion.getIs_solve());
        intent.setClass(getActivity(), LWNQuestionDetailActivity.class);
        this.startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
//        if(isResume&&getActivity()!=null){
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {Thread.sleep(100);
//                        getMyQuestionFromNetwork();
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
//
//
//
//                }
//            }).start();
//
//        }
        MobclickAgent.onPageStart("MainScreen");
       // MobclickAgent.onResume(getActivity());
    }
    private boolean isResume=false;
    @Override
    public void onPause() {
        super.onPause();

        isResume=true;
        MobclickAgent.onPageEnd("MainScreen");
        //MobclickAgent.onPause(getActivity());
    }
}
